using System;
using Gtk;

using kedhlow;

namespace kedhlow
{
	public partial class AddEditItem : Gtk.Dialog
	{
		protected Util utils = new kedhlow.Util();
		protected byte[] SerialisedTextBuffer = null;
		protected string itemTitle = null;
		protected DateTime saveTime;
		
		public string ItemTitle	{ get { return itemTitle; } }
		public byte[] ItemData	{ get { return SerialisedTextBuffer; } }
		public string ItemPlainText { get { return addEditTextView.Buffer.Text; } }
		public DateTime SaveDateTime { get { return saveTime; } }
		
		//public bool ItemTextChanged	{ get { return addEditTextView.Buffer.Modified; } }
		
		public AddEditItem ()
		{
			this.Build ();		
			addEditTextView.Buffer = utils.DefineTextTags(addEditTextView.Buffer);
			itemTitle = txtItemTitle.Text.ToString(); //Record starting title
		}
		public AddEditItem (int itemID, KDB dbc)
		{
			this.Build ();
			txtItemTitle.Text = dbc.GetItemTitle(itemID);
			itemTitle = txtItemTitle.Text.ToString(); //Record starting title
			
			addEditTextView.Buffer = utils.DefineTextTags(addEditTextView.Buffer);
			addEditTextView.Buffer = utils.DeserialiseTextBuffer(dbc.GetItemData(itemID),addEditTextView.Buffer.TagTable);
		}
		
		protected virtual void OnSaveItemActivated (object sender, System.EventArgs e)
		{
			SerialisedTextBuffer = utils.SerialiseTextBuffer(addEditTextView.Buffer);
			itemTitle = txtItemTitle.Text.ToString();
			saveTime = DateTime.Now;
			this.Respond(Gtk.ResponseType.Ok);
		}
		
		protected virtual void OnAddEditBoldActivated (object sender, System.EventArgs e)
		{
			AddRemoveTextTag("bold");
		}
		
		protected virtual void OnAddEditItalicActivated (object sender, System.EventArgs e)
		{
			AddRemoveTextTag("italic");
		}
		
		protected virtual void OnAddEditUnderlineActivated (object sender, System.EventArgs e)
		{
			AddRemoveTextTag("underline");
		}
		
		protected virtual void OnAddEditStrikethroughActivated (object sender, System.EventArgs e)
		{
			AddRemoveTextTag("strikeout");
		}
		
		protected virtual void OnAddEditClearTextActivated (object sender, System.EventArgs e)
		{
			TextView text = addEditTextView;
			text.Buffer.Clear();
		}
		
		protected void AddRemoveTextTag(string TagName)
		{
			TextView text = addEditTextView;
			if(text.Buffer.HasSelection)
			{
				TextTag tag = text.Buffer.TagTable.Lookup(TagName);
				TextIter start, end;
				text.Buffer.GetSelectionBounds(out start, out end);
				if((start.HasTag(tag))&&(end.HasTag(tag))
				||(start.HasTag(tag))&&(end.EndsTag(tag)))
				{
					text.Buffer.RemoveTag(tag,start,end);
				}
				else
				{
					text.Buffer.ApplyTag(tag,start,end);
				}
			}
		}
	}
}